package com.zby.business.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zby.business.R;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

/**
 * Created by BY on 2016/3/11.
 */
public class UpLoad extends Activity {
    private EditText name, introduce, price, discount;
    private Spinner categorySpinner, commoditySpinner;
    private ArrayAdapter categories, commodities;
    private Button upload;
    private ImageView upLoadAdd;
    private App app;
    private ArrayList categoryIndex, commodityIndex, images;
    private String commodityName, commodityIntroduce, CommodityPrice, commodityDiscount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.upload);
        initView();
        initData();
        super.onCreate(savedInstanceState);
    }

    private void initData() {
        MyAsyncTask asyncTask = new MyAsyncTask();
        try {
            String s = asyncTask.execute("getCategory").get();
            System.out.println(s);
            JSONObject object = new JSONObject(s);
            JSONArray category = object.getJSONArray("category");
            for (int i = 0; i < category.length(); i++) {
                JSONObject c = (JSONObject) category.get(i);
                categories.add(c.get("categoryName"));
                categoryIndex.add(c.get("categoryId"));
            }
            categorySpinner.setAdapter(categories);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        app = (App) getApplication();
        categoryIndex = new ArrayList();
        commodityIndex = new ArrayList();
        images = new ArrayList();
        upLoadAdd = (ImageView) findViewById(R.id.upLoadAdd);
        name = (EditText) findViewById(R.id.upLoadName);
        discount = (EditText) findViewById(R.id.discount);
        introduce = (EditText) findViewById(R.id.upLoadIntroduce);
        price = (EditText) findViewById(R.id.upLoadPrice);
        upload = (Button) findViewById(R.id.upLoadButton);
        categorySpinner = (Spinner) findViewById(R.id.categorySpinner);
        commoditySpinner = (Spinner) findViewById(R.id.commoditySpinner);
        categories = new ArrayAdapter(getApplicationContext(), R.layout.spinner_item);
        commodities = new ArrayAdapter(getApplicationContext(), R.layout.spinner_item);
        categories.setDropDownViewResource(R.layout.dropdown_item);
        commodities.setDropDownViewResource(R.layout.dropdown_item);
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.backLayout);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        upLoadAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                intent.putExtra("crop", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, 2);
            }
        });
        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                MyAsyncTask asyncTask = new MyAsyncTask();
                try {
                    String s = asyncTask.execute("getCommodityList?categoryId=" + categoryIndex.get(position)).get();
                    System.out.println(s);
                    commodityIndex.clear();
                    commodities.clear();
                    JSONObject object = new JSONObject(s);
                    JSONArray commodity = object.getJSONArray("commodity");
                    for (int i = 0; i < commodity.length(); i++) {
                        JSONObject c = (JSONObject) commodity.get(i);
                        commodities.add(c.get("commodityName"));
                        commodityIndex.add(c.get("commodityId"));
                    }
                    commoditySpinner.setAdapter(commodities);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (app.getUserId().equals("")) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(UpLoad.this);
                    alert.setMessage("登录后才可以进行该操作!");
                    alert.setPositiveButton("去登录", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(UpLoad.this, Login.class);
                            startActivity(intent);
                        }
                    });
                    alert.setNegativeButton("知道了", null);
                    alert.show();
                } else {
                    commodityName = name.getText().toString();
                    commodityIntroduce = introduce.getText().toString();
                    CommodityPrice = price.getText().toString();
                    commodityDiscount = discount.getText().toString();
                    if (Float.parseFloat(commodityDiscount) > 1) {
                        commodityDiscount = "1";
                    }
                    AsyncHttpClient client = new AsyncHttpClient();
                    RequestParams params = new RequestParams();
                    params.put("name", commodityName);
                    params.put("introduce", commodityIntroduce);
                    params.put("price", CommodityPrice);
                    params.put("discount", commodityDiscount);
                    params.put("detailId", commodityIndex.get(commoditySpinner.getSelectedItemPosition()));
                    File[] files = new File[images.size()];
                    for (int i = 0; i < images.size(); i++) {
                        File file = new File(images.get(i) + "");
                        files[i] = file;
                    }
                    try {
                        params.put("files", files);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    client.post(Util.BASE_URL + "AddCommodity", params, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int i, Header[] headers, byte[] bytes) {
                            finish();
                        }

                        @Override
                        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                            System.out.println("fail");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Util.verifyStoragePermissions(UpLoad.this);
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.upLoadImage);
        Bitmap bitmap = BitmapFactory.decodeFile(data.getData().getPath());
        ImageView image = new ImageView(getApplicationContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.width = 400;
        params.height = 220;
        image.setPadding(0, 10, 0, 10);
        image.setLayoutParams(params);
        image.setImageBitmap(bitmap);
        images.add(data.getData().getPath());
        linearLayout.addView(image, linearLayout.getChildCount() - 1);
    }


}
